package com.fangdd.logtrace;

/**
 * Created by sulong on 16-9-6.
 */
public class TraceIdThreadLocal {
    private static ThreadLocal<TraceId> localTraceId = new ThreadLocal<TraceId>() {
        @Override
        protected TraceId initialValue() {
            return TraceId.UNSET;
        }
    };

    private static ThreadLocal<Integer> lastSeq = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return -1;
        }
    };

    public static TraceId get() {
        if (localTraceId.get() == null) {
            localTraceId.set(TraceId.UNSET);
        }

        return localTraceId.get();
    }

    public static void set(TraceId traceId) {
        if (traceId == null) {
            localTraceId.set(TraceId.UNSET);
        } else {
            localTraceId.set(traceId);
        }

        lastSeq.set(-1);
    }

    public static void clear() {
        localTraceId.set(TraceId.UNSET);
        lastSeq.set(-1);
    }

    public static TraceId sequentialNext() {
        lastSeq.set(lastSeq.get() + 1);
        return new TraceId(localTraceId.get().toString() + ":" + lastSeq.get());
    }

    public static TraceId concurrentNext() {
        lastSeq.set(lastSeq.get() + 1);
        return new TraceId(localTraceId.get().toString() + "#" + lastSeq.get());
    }

}
